// 游戏棋盘和分数初始化
let board = Array(16).fill(0);
let score = 0;

// 启动游戏
function startGame() {
    board.fill(0); // 清空棋盘
    score = 0; // 重置分数
    document.getElementById('score-value').innerText = score; // 更新分数显示
    generateRandomTile(); // 生成两个随机方块
    generateRandomTile();
    updateBoard(); // 更新棋盘显示
}

// 生成随机方块
function generateRandomTile() {
    let emptyCells = board.map((value, index) => value === 0 ? index : null).filter(index => index !== null);
    if (emptyCells.length === 0) return; // 如果没有空格，返回

    let randomIndex = emptyCells[Math.floor(Math.random() * emptyCells.length)]; // 随机选择一个空格
    board[randomIndex] = Math.random() < 0.9 ? 2 : 4; // 90% 概率生成 2，10% 概率生成 4
}

// 更新棋盘显示
function updateBoard() {
    board.forEach((value, index) => {
        const cell = document.getElementById(`cell-${index}`); // 获取单元格元素
        cell.innerText = value > 0 ? value : ''; // 显示方块值
        cell.style.backgroundColor = getColor(value); // 设置方块颜色
    });
    document.getElementById('score-value').innerText = score; // 更新分数显示
}

// 根据方块值获取对应颜色
function getColor(value) {
    switch (value) {
        case 0: return "#eee4da";
        case 2: return "#eee4da";
        case 4: return "#ede0c8";
        case 8: return "#f2b179";
        case 16: return "#f59563";
        case 32: return "#f67c5f";
        case 64: return "#f67c5f";
        case 128: return "#f9f58a";
        case 256: return "#f9f58a";
        case 512: return "#c2d6e9";
        case 1024: return "#c2d6e9";
        case 2048: return "#e4c65b";
        default: return "#cdc1b4"; // 默认颜色
    }
}

// 移动方块
function move(direction) {
    let oldBoard = board.slice(); // 保存当前棋盘状态
    let moved = false; // 标记是否有方块移动

    if (direction === 'up') {
        for (let col = 0; col < 4; col++) {
            let temp = [];
            for (let row = 0; row < 4; row++) {
                if (board[row * 4 + col] !== 0) {
                    temp.push(board[row * 4 + col]);
                }
            }
            let newCol = merge(temp);
            for (let row = 0; row < 4; row++) {
                board[row * 4 + col] = newCol[row] || 0;
            }
        }
    } else if (direction === 'down') {
        for (let col = 0; col < 4; col++) {
            let temp = [];
            for (let row = 3; row >= 0; row--) {
                if (board[row * 4 + col] !== 0) {
                    temp.push(board[row * 4 + col]);
                }
            }
            let newCol = merge(temp);
            for (let row = 0; row < 4; row++) {
                board[(3 - row) * 4 + col] = newCol[row] || 0;
            }
        }
    } else if (direction === 'left') {
        for (let row = 0; row < 4; row++) {
            let temp = [];
            for (let col = 0; col < 4; col++) {
                if (board[row * 4 + col] !== 0) {
                    temp.push(board[row * 4 + col]);
                }
            }
            let newRow = merge(temp);
            for (let col = 0; col < 4; col++) {
                board[row * 4 + col] = newRow[col] || 0;
            }
        }
    } else if (direction === 'right') {
        for (let row = 0; row < 4; row++) {
            let temp = [];
            for (let col = 3; col >= 0; col--) {
                if (board[row * 4 + col] !== 0) {
                    temp.push(board[row * 4 + col]);
                }
            }
            let newRow = merge(temp);
            for (let col = 0; col < 4; col++) {
                board[row * 4 + (3 - col)] = newRow[col] || 0;
            }
        }
    }

    // 检查是否有移动
    if (!oldBoard.every((value, index) => value === board[index])) {
        moved = true;
        generateRandomTile(); // 移动后生成新的随机方块
    }

    updateBoard(); // 更新棋盘显示
    return moved; // 返回是否有移动
}

// 合并逻辑
function merge(line) {
    let newLine = [];
    let scoreIncrease = 0;

    for (let i = 0; i < line.length; i++) {
        if (line[i] === line[i + 1]) {
            newLine.push(line[i] * 2); // 合并
            scoreIncrease += line[i] * 2; // 更新分数
            i++; // 跳过下一个元素
        } else {
            newLine.push(line[i]); // 直接添加
        }
    }

    // 填充零
    while (newLine.length < 4) {
        newLine.push(0);
    }

    score += scoreIncrease; // 更新总分
    return newLine; // 返回合并后的行
}

// 检查游戏是否结束
function checkGameOver() {
    if (board.includes(0)) return false; // 还有空格，游戏未结束

    // 检查是否有相邻的相同方块
    for (let row = 0; row < 4; row++) {
        for (let col = 0; col < 4; col++) {
            if (col < 3 && board[row * 4 + col] === board[row * 4 + (col + 1)]) {
                return false; // 右边有相同方块
            }
            if (row < 3 && board[row * 4 + col] === board[(row + 1) * 4 + col]) {
                return false; // 下边有相同方块
            }
        }
    }

    return true; // 没有可移动的方块，游戏结束
}

// 处理用户输入
document.addEventListener('keydown', function(event) {
    switch (event.key) {
        case 'ArrowUp':
            if (move('up')) {
                if (checkGameOver()) {
                    alert('游戏结束！');
                }
            }
            break;
        case 'ArrowDown':
            if (move('down')) {
                if (checkGameOver()) {
                    alert('游戏结束！');
                }
            }
            break;
        case 'ArrowLeft':
            if (move('left')) {
                if (checkGameOver()) {
                    alert('游戏结束！');
                }
            }
            break;
        case 'ArrowRight':
            if (move('right')) {
                if (checkGameOver()) {
                    alert('游戏结束！');
                }
            }
            break;
    }
});

// 处理刷新按钮点击事件
document.getElementById('reset-button').addEventListener('click', function() {
    startGame(); // 重新启动游戏
});

// 处理按钮点击事件
document.getElementById('up-button').addEventListener('click', function() {
    if (move('up')) {
        if (checkGameOver()) {
            alert('游戏结束！');
        }
    }
});

document.getElementById('down-button').addEventListener('click', function() {
    if (move('down')) {
        if (checkGameOver()) {
            alert('游戏结束！');
        }
    }
});

document.getElementById('left-button').addEventListener('click', function() {
    if (move('left')) {
        if (checkGameOver()) {
            alert('游戏结束！');
        }
    }
});

document.getElementById('right-button').addEventListener('click', function() {
    if (move('right')) {
        if (checkGameOver()) {
            alert('游戏结束！');
        }
    }
});

// 启动游戏
startGame();
// 更新时钟的函数
function updateClock() {
    const clockElement = document.getElementById('clock');
    const now = new Date();
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    clockElement.innerText = `${hours}:${minutes}:${seconds}`;
}

// 更新时钟的函数
function updateClock() {
    const clockElement = document.getElementById('clock');
    const now = new Date();
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    clockElement.innerText = `${hours}:${minutes}:${seconds}`;
}

// 每秒更新一次时钟
setInterval(updateClock, 1000);

// 更新计时器的函数
function updateTimer() {
    const timerElement = document.getElementById('timer');
    timerElement.innerText = `Time: ${seconds} seconds`;
}

// 启动计时器
function startTimer() {
    seconds = 0;
    timerInterval = setInterval(() => {
        seconds++;
        updateTimer();
    }, 1000);
}

// 重置计时器
function resetGame() {
    clearInterval(timerInterval);
    startTimer();
}

document.addEventListener('DOMContentLoaded', () => {
    startTimer(); // 页面加载时启动计时器

    document.getElementById('reset-button').addEventListener('click', () => {
        resetGame(); // 点击“刷新游戏”按钮时重置计时器
    });
});

// 初始化时钟显示
updateClock();
// 初始化时钟显示
updateClock();